<template>
    <div style="height: 100%">
        <div class="box-top" ref="topboxref">
            <div class="box-top-title">策略信息</div>
            <el-row>
                <el-col :span="6" class="box-top-content">
                    <div class="box-top-content-title">策略名称</div>
                    <div class="box-top-content-text">{{ name }}</div>
                </el-col>
                <el-col v-if="templateName" :span="6" class="box-top-content">
                    <div class="box-top-content-title">策略模版</div>
                    <div class="box-top-content-text">{{ templateName }}</div>
                </el-col>
            </el-row>
        </div>
        <div style="padding-bottom: 16px; height: calc(100% - 105px); box-sizing: border-box">
            <el-row :gutter="16" style="height: 100%">
                <el-col :span="6" :style="{ height: topboxheight }">
                    <div v-loading="leftboxLoading" class="box-left">
                        <div ref="btns" class="btns">
                            <div class="btn-box" @click="openFirst">
                                <text class="closeText">新增一级部件</text>
                            </div>
                            <div class="btn-box" @click="openSecond" style="margin-left: 16px"><text
                                    class="closeText">新增二级部件</text></div>
                        </div>
                        <div>
                            <text v-for="(item, index) in typeList" class="unchecked"
                                :class="{ select: typeIndex == item.value, 'ml-16': index != 0 }"
                                @click="changeTypeIndex(item.value)">{{
                                    item.label
                                }}</text>
                        </div>
                        <el-input maxlength="30" class="search" v-model="search" placeholder="请输入字典类别" :suffix-icon="Search"
                            @input="searchInput" />
                        <div class="scroll" style="overflow: auto" :style="{ height: scrollHeight }">
                            <el-tree style="padding-right: 10px" highlight-current ref="treeRef" :data="treeData"
                                :props="defaultProp" node-key="id" :expand-on-click-node="true" @node-click="treeClick"
                                :filter-node-method="filterNode" :default-expand-all="true" :default-checked-keys="nowData">
                                <template #default="{ node, data }">
                                    <div class="custom-tree-node">
                                        <div class="tree-flex">
                                            <!-- <i v-if="data.depth == 0" class="iconfont icon-a--1 selectd" /> -->
                                            <i class="iconfont icon-wenjian" v-if="data.depth == 1"
                                                style="font-size: 16px; color: #ebebeb; margin-right: 10px"></i>
                                            <img src="@/assets/image/equipmentManagement/iconfolder.png" class="image"
                                                v-if="data.depth == 0" />
                                            <img src="@/assets/image/equipmentManagement/backup.png" class="images"
                                                v-if="data.depth == 1" />
                                            {{ node.label }}
                                        </div>
                                        <div class="operate">
                                            <el-tooltip effect="dark" content="编辑" placement="bottom" :hide-after="0">
                                                <i class="iconfont icon-bianji icon" @click.stop="edit(data)"></i>
                                            </el-tooltip>
                                            <el-tooltip effect="dark" content="删除" placement="bottom" :hide-after="0">
                                                <i class="iconfont icon-shanchu icon" style="margin-left: 9px"
                                                    @click.stop="remove(data)"></i>
                                            </el-tooltip>
                                        </div>
                                    </div>
                                </template>
                            </el-tree>
                        </div>
                    </div>
                </el-col>
                <el-col :span="18" style="height: 100%">
                    <div v-loading="topLoading" class="right-top-box" style="height: 135px" ref="rightbox">
                        <div class="period">
                            <text class="period-title">计划周期</text>
                            <div class="right-top-box-btn" @click="editPlan(selectData)">编辑计划</div>
                        </div>
                        <el-table class="table" :data="planData" style="width: 100%; padding-top: 16px; height: 110px">
                            <el-table-column prop="maintenanceType" label="一级保养" width="180">
                                <template #default="scope">
                                    <div v-if="scope.row.maintenanceType == 1">每天</div>
                                    <div v-else></div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="weekly" label="二级保养（周计划）" minWidth="180">
                                <template #default="scope">
                                    {{ weekChange(scope.row.weekly) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="monthly" label="二级保养（月计划）" minWidth="180" />
                            <el-table-column prop="season" label="二级保养（季计划）" minWidth="180">
                                <template #default="scope">
                                    {{ scope.row.season == "[]" ? "" : scope.row.season }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="yearly" label="二级保养（年计划）" minWidth="180">
                                <template #default="scope">
                                    {{ scope.row.yearly == "[]" ? "" : scope.row.yearly }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="everyDay" label="二级保养（间隔计划）" minWidth="180">
                                <template #default="scope">
                                    <text v-if="scope.row.everyDay">每隔{{ scope.row.everyDay }}天执行一次</text>
                                    <text v-if="scope.row.everyDay && scope.row.isWeekend">,</text>
                                    <text v-if="scope.row.isWeekend">仅工作日</text>
                                </template>
                            </el-table-column>
                            <el-table-column prop="customerDay" label="二级保养（自定义计划）" minWidth="180">
                                <template #default="scope">
                                    {{ scope.row.customerDay == "[]" ? "" : scope.row.customerDay }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div v-loading="bottomLoading" class="right-bottom-box" :style="{ height: rightboxheight }">
                        <div class="check">
                            <text class="check-title">检查项</text>
                            <div class="check-btns">
                                <div class="check-add" @click="addthird(selectData, '编辑三级部件')">编辑三级部件</div>
                            </div>
                        </div>
                        <el-table ref="tableRef" @select="selectChanges" @select-all="selectAllChanges" :data="thirdData"
                            style="width: 100%; padding-top: 16px; height: calc(100% - 90px)">
                            <el-table-column prop="structureName" label="三级部件" minWidth="180" />
                            <el-table-column type="index" :index="indexMethod" label="序号" minWidth="180" />
                            <el-table-column prop="inspectionItemName" label="检查项" minWidth="180" />
                            <el-table-column prop="inspectionResultText" label="检查结果" minWidth="180" />
                            <el-table-column prop="disposalMethodText" label="处置方式" minWidth="180" />
                        </el-table>
                        <div class="pagination" v-if="total !== -1">
                            <el-pagination layout="sizes, prev, pager, next, jumper" :total="total" small
                                @update:current-page="currentChange" @update:page-size="sizeChange" />
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
    </div>
    <div>
        <el-dialog destroy-on-close v-model="first" :title="firstTitle" :close-on-click-modal="false" width="30%">
            <el-form :model="structureParam" label-width="68px" :rules="structureParamRules" hide-required-asterisk
                ref="structureParamRef">
                <el-row style="overflow: auto;max-height: 600px;">
                    <el-col :span="24">
                        <el-form-item label="策略名称">
                            <text>{{ name }}</text>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="一级机构" prop="name">
                            <el-select v-if="firstTitle !== '编辑计划'" filterable v-model="structureParam.name"
                                placeholder="请选择一级机构">
                                <el-option v-for="item in firstOption" :key="item.label" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                            <text v-else>{{ structureParam.name }}</text>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label-width="0">
                            <div class="checkbox">
                                <el-checkbox v-model="maintainFirst" label="一级保养（每天）" @change="maintainFirstChange" />
                                <el-checkbox v-model="maintainSecond" label="二级保养（自定义）" @change="maintainSecondChange" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-form-item label-width="0" style="margin-left: 24px" :class="{ none: !maintainSecond }">
                        <div class="checkbox">
                            <div class="flex">
                                <el-checkbox v-model="weekly" class="mr-8" @change="weeklyChange" label="周计划" />
                                <el-select v-model="planParams.weekly" placeholder="请选择周计划" multiple :disabled="!weekly">
                                    <el-option v-for="item in week" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </div>
                            <div class="flex">
                                <el-checkbox v-model="monthly" class="mr-8" label="月计划" @change="monthlyChange" />
                                <el-select v-model="planParams.monthly" placeholder="请选择月计划" multiple :disabled="!monthly">
                                    <el-option v-for="item in month" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </div>
                            <div class="flex">
                                <el-checkbox v-model="season" class="mr-8" label="季计划" @change="seasonChange" />
                                <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="planParams.season"
                                    type="dates" placeholder="请选择季计划" :size="size" :disabled="!season" />
                            </div>
                            <div class="flex">
                                <el-checkbox v-model="yearly" class="mr-8" label="年计划" @change="yearlyChange" />
                                <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="planParams.yearly"
                                    type="dates" placeholder="请选择年计划" :size="size" :disabled="!yearly" />
                            </div>
                            <div class="flex">
                                <el-checkbox v-model="everyDay" class="mr-8" label="间隔计划" @change="everyDayChange" />
                                <text class="flex-text">每隔</text>
                                <el-input maxlength="30" oninput="value=value.replace(/^0|[^0-9]/g,'')" prop="everyDay"
                                    type="number" v-model="planParams.everyDay" :disabled="!everyDay"
                                    style="width: 40px; margin: 0 8px" /><text class="flex-text">天执行</text>
                            </div>
                            <div class="flex">
                                <el-radio-group v-model="radio" style="padding-right: 12px">
                                    <el-radio :label="true" @click.native.prevent="isWeekendClick(true)">仅执行工作日</el-radio>
                                </el-radio-group>
                            </div>
                            <div class="flex">
                                <el-checkbox class="mr-8" label="自定义" v-model="customerDay" @change="customerDayChange" />
                                <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                                    v-model="planParams.customerDay" type="dates" placeholder="请自定义计划" :size="size"
                                    :disabled="!customerDay" />
                            </div>
                        </div>
                    </el-form-item>
                </el-row>
                <div class="button">
                    <div class="submit" @click="firstSubmit">
                        <text class="submitText">下一步</text>
                    </div>
                    <div class="close" @click="firstClose">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog destroy-on-close v-model="people" title="选择维保分派人员" :close-on-click-modal="false" width="30%">
            <el-form :model="structureParam" label-width="68px" :rules="structureParamRuless" hide-required-asterisk
                ref="structureParamRefs">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="分派人员" prop="personnelId">
                            <el-select v-model="structureParam.personnelId" placeholder="请选择分派人员">
                                <el-option v-for="item in managerOption" :key="item.value" :label="item.label"
                                    :value="item.value" :disabled="item.disabled != 0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="button">
                    <div class="submit" @click="peopleSubmit">
                        <text class="submitText">提交</text>
                    </div>
                    <div class="close" @click="peopleClose">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog destroy-on-close v-model="second" :title="secondTitle" :close-on-click-modal="false" width="60%">
            <el-form v-loading="secondLoading" :model="structureParam" label-width="68px" :rules="structureParamRulesss"
                hide-required-asterisk ref="structureParamRefss">
                <el-row>
                    <el-col :span="12">
                        <text class="second-title">策略名称</text>
                        <text class="second-text">起重设备运维策略</text>
                    </el-col>
                    <el-col :span="12">
                        <text class="second-title">一级部件</text>
                        <text class="second-text">{{ treeChangeData.name }}</text>
                    </el-col>
                    <el-col style="padding-top: 16px" :span="24">
                        <el-form-item label="二级部件" prop="name">
                            <el-select v-if="secondTitle == '新增二级机构'" filterable v-model="structureParam.name"
                                placeholder="请选择二级部件">
                                <el-option v-for="item in secondOption" :key="item.label" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                            <text v-else>{{ structureParam.name }}</text>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-table :style="{ height: dialogTableHeight }" ref="secondTableRef" :data="secondData"
                    style="width: 100%; padding-top: 16px" @select="selectChange" @select-all="selectAllChange">
                    <el-table-column type="selection"></el-table-column>
                    <el-table-column type="index" :index="indexMethod" label="序号" width="180" />
                    <el-table-column prop="structureName" label="三级部件" width="180" />
                    <el-table-column prop="templateName" label="模板名称" width="180" />
                    <el-table-column prop="remark" label="模板备注" width="180" />
                    <el-table-column prop="count" label="检查项数量" width="180" />
                </el-table>
                <div class="second-btn">
                    <div class="submit" @click="secondSubmit">
                        <text class="submitText">确定</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>
<script setup>
import { Search } from "@element-plus/icons-vue";
import { ref, computed, watch, nextTick, onMounted, reactive } from "vue";
import { week, month, defaultProp, structureParamRules, structureParamRuless, structureParamRulesss } from "./policyTemplateConfig";
import { getlistasync } from "@/service/api/equipmentManagement.js";
import { useRouter } from "vue-router";
import {
    getinspectionitemtemplist,
    addsecordstructure,
    getstructuretypelist,
    getstructuretree,
    addfirststructure,
    getbasicsstructurefirstnamelist,
    getbasicsstructuresecondnamelist,
    getplancycledetail,
    editfirststructure,
    batchdeletefirststructure,
    batchdeletesecondstructure,
    editsecordstructure,
    getthirdstructurepage
} from "@/service/api/tacticalManagement.js";

const router = useRouter();
const id = computed(() => router.currentRoute.value.query.id);
const name = computed(() => router.currentRoute.value.query.name);
const templateName = computed(() => router.currentRoute.value.query.templateName);
const first = ref(false);
const people = ref(false);
const second = ref(false);
const firstTitle = ref();
const secondTitle = ref();
const typeList = ref([]);
const typeIndex = ref(0);
const treeData = ref();
const search = ref("");
const treeRef = ref();
const planParams = ref();
const structureParam = ref();
const maintainFirst = ref(true);
const maintainSecond = ref(false);
const firstOption = ref([]);
const weekly = ref(false);
const monthly = ref(false);
const season = ref(false);
const yearly = ref(false);
const everyDay = ref(false);
const customerDay = ref(false);
const radio = ref(false);
const managerOption = ref([]);
const structureParamRef = ref(null);
const structureParamRefs = ref(null);
const structureParamRefss = ref(null);
const secondOption = ref([]);
const selectData = ref({});
const insItemTemplateIds = ref([]);
const secondData = ref();
const planData = ref();
const treeChangeData = ref({});
const secondTableRef = ref(null);
const delTemplateIds = ref([]);
const thirdData = ref([]);
const topboxref = ref();
const topboxheight = ref();
const rightbox = ref();
const rightboxheight = ref();
const nowData = ref([]);
const total = ref(-1);
const pagination = reactive({ page: 1, pageSize: 10 });
let allSelectTable = [];
const tableRef = ref(null);
const secondLoading = ref(false);
const topLoading = ref(false);
const bottomLoading = ref(false);
const btns = ref();
const scrollHeight = ref();
const leftboxLoading = ref(true);
const dialogTableHeight = ref();
const parentId = ref();
const addTemplateIds = ref([])
const insItemTemplateIdsCopy = ref([])

getstructuretypelist()
    .then((res) => {
        if (res.code === 200) {
            typeList.value = res.data.map((item) => ({ label: item.name, value: item.value }));
            typeIndex.value = typeList.value[0].value;
            getstructuretree({ strategyId: id.value, structureType: typeList.value[0].value }).then((r) => {
                if (r.code === 200) {
                    treeData.value = r.data;
                }
                leftboxLoading.value = false;
            });
        }
    })
    .catch(() => {
        leftboxLoading.value = false;
    });
getbasicsstructurefirstnamelist().then((res) => {
    if (res.code === 200) {
        firstOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
    }
});
getbasicsstructuresecondnamelist().then((res) => {
    if (res.code === 200) {
        secondOption.value = res.data.map((item) => ({ label: item.name, value: item.Vvlue }));
    }
});
watch(search, (val) => {
    treeRef.value.filter(val);
});
onMounted(() => {
    dialogTableHeight.value = document.querySelector("body").clientHeight * 0.4 + "px";
    topboxheight.value = document.querySelector("body").clientHeight - topboxref.value.offsetHeight - 56 - 40 - 33 + "px";
    rightboxheight.value = document.querySelector("body").clientHeight - topboxref.value.offsetHeight - rightbox.value.offsetHeight - 56 - 40 - 32 - 16 - 33 + "px";
    scrollHeight.value = document.querySelector("body").clientHeight - topboxref.value.offsetHeight - btns.value.offsetHeight - 56 - 40 - 32 - 16 - 19 - 64 - 16 + "px";
});

const weekChange = (value) => {
    if (value != null) {
        var data = "";
        for (let index = 0; index < value.length; index++) {
            for (let i = 0; i < week.length; i++) {
                if (value[index] == week[i].value) {
                    data += week[i].label + ",";
                }
            }
        }
        data = data.substring(0, data.length - 1);
        return data;
    }
};
const currentChange = async (page) => {
    pagination.page = page;
    const loadingInstance = ElLoading.service();
    await getthirdstructurepage({ structureId: selectData.value.id, pageNum: pagination.page, pageSize: pagination.pageSize, depth: selectData.value.depth })
        .then((res) => {
            if (res.code === 200) {
                thirdData.value = res.data.list;
                total.value = res.data.total;
            }
            loadingInstance.close();
        })
        .catch(() => {
            loadingInstance.close();
        });
    allSelectTable[pagination.page - 1]?.forEach((row) => {
        const find = thirdData.value.find((item) => item.id === row.id);
        tableRef.value.toggleRowSelection(find, true);
    });
};
const sizeChange = (pageSize) => {
    pagination.pageSize = pageSize;
    const loadingInstance = ElLoading.service();
    getthirdstructurepage({ structureId: selectData.value.id, pageNum: pagination.page, pageSize: pagination.pageSize, depth: selectData.value.depth })
        .then((res) => {
            if (res.code === 200) {
                thirdData.value = res.data.list;
                total.value = res.data.total;
            }
            loadingInstance.close();
        })
        .catch(() => {
            loadingInstance.close();
        });
};
const selectChanges = (value) => {
    allSelectTable[pagination.page - 1] = value;
};
const selectAllChanges = (value) => {
    allSelectTable[pagination.page - 1] = value;
};
const edit = (data) => {
    console.log(data);
    if (data.depth == 0) {
        getplancycledetail(data.id).then((res) => {
            if (res.code === 200) {
                weekly.value = false;
                monthly.value = false;
                season.value = false;
                yearly.value = false;
                everyDay.value = false;
                customerDay.value = false;
                radio.value = res.data.isWeekend;
                maintainFirst.value = true;
                maintainSecond.value = false;
                planParams.value = {
                    id: res.data.id,
                    strategyId: res.data.strategyId,
                    maintenanceType: res.data.maintenanceType,
                    weekly: "",
                    season: [],
                    monthly: "",
                    yearly: [],
                    everyDay: "",
                    customerDay: [],
                    isWeekend: res.data.isWeekend
                };
                if (res.data.maintenanceType == 2) {
                    maintainFirst.value = false;
                    maintainSecond.value = true;
                    if (res.data.weekly != "") {
                        weekly.value = true;
                        planParams.value.weekly = res.data.weekly.split(",").map((item) => parseInt(item));
                    }
                    if (res.data.monthly != "") {
                        monthly.value = true;
                        planParams.value.monthly = res.data.monthly.split(",").map((item) => parseInt(item));
                    }
                    if (res.data.season != "[]") {
                        season.value = true;
                        planParams.value.season = res.data.season.split(",");
                    }
                    if (res.data.yearly != "[]") {
                        yearly.value = true;
                        planParams.value.yearly = res.data.yearly.split(",");
                    }
                    if (res.data.everyDay != null) {
                        everyDay.value = true;
                        planParams.value.everyDay = res.data.everyDay;
                    }
                    if (res.data.customerDay != "[]") {
                        customerDay.value = true;
                        planParams.value.customerDay = res.data.customerDay.split(",");
                    }
                }
                structureParam.value = {
                    id: data.id,
                    strategyId: data.strategyId,
                    name: data.name,
                    parentId: data.parentId,
                    depth: data.depth,
                    structureType: data.structureType,
                    personnelId: data.personnelId
                };
                firstTitle.value = "修改一级机构";
                first.value = true;
            }
        });
    } else {
        insItemTemplateIds.value = [];
        secondLoading.value = true;
        getinspectionitemtemplist({ id: data.id })
            .then((res) => {
                if (res.code === 200) {
                    secondData.value = res.data;
                    secondData.value.forEach((item) => {
                        if (item.checked) {
                            insItemTemplateIds.value.push(item.id);
                            nextTick(() => {
                                secondTableRef.value.toggleRowSelection(item, true);
                            });
                        }
                    });
                    insItemTemplateIdsCopy.value = insItemTemplateIds.value
                }
                secondLoading.value = false;
            })
            .catch(() => {
                secondLoading.value = false;
            });
        treeChangeData.value = treeData.value.find((item) => item.id == data.parentId);
        structureParam.value = {
            id: data.id,
            strategyId: data.strategyId,
            name: data.name,
            parentId: data.parentId,
            depth: data.depth,
            structureType: data.structureType,
            personnelId: data.personnelId
        };
        second.value = true;
        secondTitle.value = "修改二级部件";
    }
};
const addthird = (data, title) => {
    if (data.depth != 1) {
        ElMessage({
            message: "请选择二级机构后再进行操作",
            type: "warning"
        });
        return;
    }
    insItemTemplateIds.value = [];
    secondLoading.value = true;
    getinspectionitemtemplist({ id: data.id })
        .then((res) => {
            if (res.code === 200) {
                secondData.value = res.data;
                secondData.value.forEach((item) => {
                    if (item.checked) {
                        insItemTemplateIds.value.push(item.id);
                        nextTick(() => {
                            secondTableRef.value.toggleRowSelection(item, true);
                        });
                    }
                });
                insItemTemplateIdsCopy.value = insItemTemplateIds.value
            }
            secondLoading.value = false;
        })
        .catch(() => {
            secondLoading.value = false;
        });
    treeChangeData.value = treeData.value.find((item) => item.id == data.parentId);
    structureParam.value = {
        id: data.id,
        strategyId: data.strategyId,
        name: data.name,
        parentId: data.parentId,
        depth: data.depth,
        structureType: data.structureType,
        personnelId: data.personnelId
    };
    second.value = true;
    secondTitle.value = title;
};
const editPlan = (data) => {
    if (data.depth != 0) {
        ElMessage({
            message: "请选择一级机构后再进行编辑计划操作",
            type: "warning"
        });
        return;
    }
    getplancycledetail(data.id).then((res) => {
        if (res.code === 200) {
            weekly.value = false;
            monthly.value = false;
            season.value = false;
            yearly.value = false;
            everyDay.value = false;
            customerDay.value = false;
            radio.value = res.data.isWeekend;
            maintainFirst.value = true;
            maintainSecond.value = false;
            planParams.value = {
                id: res.data.id,
                strategyId: res.data.strategyId,
                maintenanceType: res.data.maintenanceType,
                weekly: "",
                season: [],
                monthly: "",
                yearly: [],
                everyDay: "",
                customerDay: [],
                isWeekend: res.data.isWeekend
            };
            if (res.data.maintenanceType == 2) {
                maintainFirst.value = false;
                maintainSecond.value = true;
                if (res.data.weekly != "") {
                    weekly.value = true;
                    planParams.value.weekly = res.data.weekly.split(",").map((item) => parseInt(item));
                }
                if (res.data.monthly != "") {
                    monthly.value = true;
                    planParams.value.monthly = res.data.monthly.split(",").map((item) => parseInt(item));
                }
                if (res.data.season != "[]") {
                    season.value = true;
                    planParams.value.season = res.data.season.split(",");
                }
                if (res.data.yearly != "[]") {
                    yearly.value = true;
                    planParams.value.yearly = res.data.yearly.split(",");
                }
                if (res.data.everyDay != null) {
                    everyDay.value = true;
                    planParams.value.everyDay = res.data.everyDay;
                }
                if (res.data.customerDay != "[]") {
                    customerDay.value = true;
                    planParams.value.customerDay = res.data.customerDay.split(",");
                }
            }
            structureParam.value = {
                id: data.id,
                strategyId: data.strategyId,
                name: data.name,
                parentId: data.parentId,
                depth: data.depth,
                structureType: data.structureType,
                personnelId: data.personnelId
            };
            firstTitle.value = "编辑计划";
            first.value = true;
        }
    });
};
const remove = (data) => {
    ElMessageBox.confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: ""
    }).then(() => {
        const loadingInstance = ElLoading.service();
        if (data.depth == 0) {
            batchdeletefirststructure({
                ids: [data.id]
            })
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            type: "success",
                            message: "删除成功"
                        });
                    }
                    loadingInstance.close();
                    selectData.value = {};
                    planData.value = [];
                    thirdData.value = [];
                    refresh();
                })
                .catch(() => {
                    loadingInstance.close();
                });
        } else {
            batchdeletesecondstructure({
                ids: [data.id]
            })
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            type: "success",
                            message: "删除成功"
                        });
                    }
                    loadingInstance.close();
                    selectData.value = {};
                    planData.value = [];
                    thirdData.value = [];
                    refresh();
                })
                .catch(() => {
                    loadingInstance.close();
                });
        }
    });
};
const selectChange = (value) => {
    insItemTemplateIds.value = value.map((item) => item.id);
};
const selectAllChange = (value) => {
    insItemTemplateIds.value = value.map((item) => item.id);
};
const changeTypeIndex = (value) => {
    thirdData.value = [];
    planData.value = [];
    selectData.value = {};
    typeIndex.value = value;
    leftboxLoading.value = true;
    getstructuretree({ strategyId: id.value, structureType: value })
        .then((r) => {
            if (r.code === 200) {
                treeData.value = r.data;
            }
            leftboxLoading.value = false;
        })
        .catch(() => {
            leftboxLoading.value = false;
        });
};
const weeklyChange = (value) => {
    if (!value) {
        planParams.value.weekly = "";
    }
};
const monthlyChange = (value) => {
    if (!value) {
        planParams.value.monthly = "";
    }
};
const seasonChange = (value) => {
    if (!value) {
        planParams.value.season = [];
    }
};
const yearlyChange = (value) => {
    if (!value) {
        planParams.value.yearly = [];
    }
};
const everyDayChange = (value) => {
    if (!value) {
        planParams.value.everyDay = "";
    }
};
const customerDayChange = (value) => {
    if (!value) {
        planParams.value.customerDay = [];
    }
};
const isWeekendClick = (value) => {
    radio.value = radio.value == value ? !value : value;
    planParams.value.isWeekend = radio.value;
};
const maintainFirstChange = () => {
    if (maintainSecond.value) {
        maintainSecond.value = false;
    }
    maintainFirst.value = true;
    weekly.value = false;
    monthly.value = false;
    season.value = false;
    yearly.value = false;
    everyDay.value = false;
    customerDay.value = false;
    radio.value = false;
    maintainSecond.value = false;
    planParams.value.weekly = "";
    planParams.value.season = [];
    planParams.value.monthly = "";
    planParams.value.yearly = [];
    planParams.value.everyDay = "";
    planParams.value.customerDay = [];
    planParams.value.maintenanceType = 1;
    planParams.value.isWeekend = false;
};
const maintainSecondChange = () => {
    if (maintainFirst.value) {
        maintainFirst.value = false;
    }
    maintainSecond.value = true;
    planParams.value.maintenanceType = 2;
};
const filterNode = (value, data) => {
    if (!value) return true;
    return data.name.includes(value);
};
const treeClick = (node) => {
    thirdData.value = [];
    selectData.value = node;
    treeChangeData.value = node;
    parentId.value = node.id;
    allSelectTable = [];
    if (node.depth == 1) {
        parentId.value = treeData.value.find((item) => item.id == node.parentId).id;
    }
    topLoading.value = true;
    getplancycledetail(parentId.value)
        .then((res) => {
            if (res.code === 200) {
                if (res.data == null) {
                    planData.value = [];
                } else {
                    planData.value = [res.data];
                }
            }
            topLoading.value = false;
        })
        .catch(() => {
            topLoading.value = false;
        });
    bottomLoading.value = true;
    getthirdstructurepage({ structureId: node.id, pageNum: pagination.page, pageSize: pagination.pageSize, depth: node.depth })
        .then((res) => {
            if (res.code === 200) {
                thirdData.value = res.data.list;
                total.value = res.data.total;
            }
            bottomLoading.value = false;
        })
        .catch(() => {
            bottomLoading.value = false;
        });
};

const openFirst = () => {
    weekly.value = false;
    monthly.value = false;
    season.value = false;
    yearly.value = false;
    everyDay.value = false;
    customerDay.value = false;
    radio.value = false;
    maintainFirst.value = true;
    maintainSecond.value = false;
    planParams.value = {
        id: 0,
        strategyId: id.value,
        maintenanceType: 1,
        weekly: "",
        season: [],
        monthly: "",
        yearly: [],
        everyDay: "",
        customerDay: [],
        isWeekend: false
    };
    structureParam.value = {
        id: 0,
        strategyId: id.value,
        name: "",
        parentId: 0,
        depth: 0,
        structureType: typeIndex.value,
        personnelId: ""
    };
    firstTitle.value = "新增一级机构";
    first.value = true;
};
const openSecond = () => {
    if (Object.keys(selectData.value).length == 0) {
        ElMessage({
            message: "请选择一级机构后再新增二级机构",
            type: "warning"
        });
        return;
    }
    if (selectData.value.depth != 0) {
        ElMessage({
            message: "请选择一级机构后再新增二级机构",
            type: "warning"
        });
        return;
    }
    secondLoading.value = true;
    getinspectionitemtemplist({ id: 0 })
        .then((res) => {
            if (res.code === 200) {
                secondData.value = res.data;
            }
            secondLoading.value = false;
        })
        .catch(() => {
            secondLoading.value = false;
        });
    structureParam.value = {
        id: 0,
        strategyId: id.value,
        name: "",
        parentId: selectData.value.id,
        depth: 1,
        structureType: typeIndex.value,
        personnelId: selectData.value.personnelId
    };
    secondTitle.value = "新增二级机构";
    second.value = true;
};
const firstClose = () => {
    first.value = false;
};
const firstSubmit = () => {
    if (!structureParamRef.value) return;
    structureParamRef.value.validate((valid) => {
        if (valid) {
            getlistasync({}).then((res) => {
                if (res.code === 200) {
                    managerOption.value = res.data.map((item) => ({ label: item.name, value: item.value, disabled: item.state }));
                }
            });
            first.value = false;
            people.value = true;
        }
    });
};
const peopleClose = () => {
    people.value = false;
};
const peopleSubmit = () => {
    if (!structureParamRefs.value) return;
    structureParamRefs.value.validate((valid) => {
        if (valid) {
            structureParam.value.structureType = typeIndex.value;
            const loadingInstance = ElLoading.service();
            if (firstTitle.value == "新增一级机构") {
                if (planParams.value.weekly) {
                    planParams.value.weekly = planParams.value.weekly.join();
                }
                if (planParams.value.monthly) {
                    planParams.value.monthly = planParams.value.monthly.join();
                }
                addfirststructure({ structureParamReq: structureParam.value, planParamsReq: planParams.value })
                    .then((res) => {
                        if (res.code === 200) {
                            ElMessage({
                                message: "新增成功",
                                type: "success"
                            });
                        }
                        loadingInstance.close();
                        people.value = false;
                        refresh();
                    })
                    .catch(() => {
                        loadingInstance.close();
                    });
            } else {
                if (planParams.value.weekly) {
                    planParams.value.weekly = planParams.value.weekly.join();
                }
                if (planParams.value.monthly) {
                    planParams.value.monthly = planParams.value.monthly.join();
                }
                editfirststructure({ structureParamReq: structureParam.value, planParamsReq: planParams.value })
                    .then((res) => {
                        if (res.code === 200) {
                            ElMessage({
                                message: "修改成功",
                                type: "success"
                            });
                        }
                        loadingInstance.close();
                        people.value = false;
                        refresh();
                    })
                    .catch(() => {
                        loadingInstance.close();
                    });
            }
        }
    });
};
const refresh = () => {
    topLoading.value = true;
    getplancycledetail(parentId.value)
        .then((res) => {
            if (res.code === 200) {
                if (res.data == null) {
                    planData.value = [];
                } else {
                    planData.value = [res.data];
                }
            }
            topLoading.value = false;
        })
        .catch(() => {
            topLoading.value = false;
        });
    if (Object.keys(selectData.value).length) {
        bottomLoading.value = true;
        getthirdstructurepage({ structureId: selectData.value.id, pageNum: pagination.page, pageSize: pagination.pageSize, depth: selectData.value.depth })
            .then((res) => {
                if (res.code === 200) {
                    thirdData.value = res.data.list;
                    total.value = res.data.total;
                }
                bottomLoading.value = false;
            })
            .catch(() => {
                bottomLoading.value = false;
            });
    }

    leftboxLoading.value = true;
    getstructuretree({ strategyId: id.value, structureType: typeIndex.value })
        .then((r) => {
            if (r.code === 200) {
                treeData.value = r.data;
                nowData.value = [selectData.value.id]
            }
            leftboxLoading.value = false;
            if (Object.keys(selectData.value).length) {
                nextTick(() => {
                    treeRef.value.setCurrentNode(selectData.value, true);
                });
            }

        })
        .catch(() => {
            leftboxLoading.value = false;
        });
    insItemTemplateIds.value = [];
};
const secondSubmit = () => {
    if (!structureParamRefss.value) return;
    structureParamRefss.value.validate((valid) => {
        if (valid) {
            secondLoading.value = true;
            if (secondTitle.value == "新增二级机构") {
                addsecordstructure({ structureParamReq: structureParam.value, insItemTemplateIds: insItemTemplateIds.value })
                    .then((res) => {
                        if (res.code === 200) {
                            ElMessage({
                                message: "新增成功",
                                type: "success"
                            });
                        }

                        secondLoading.value = false;
                        second.value = false;
                        refresh();
                    })
                    .catch(() => {
                        secondLoading.value = false;
                    });
            } else {
                addTemplateIds.value = []
                delTemplateIds.value = []
                insItemTemplateIdsCopy.value.forEach((item) => {
                    if (insItemTemplateIds.value.filter((v) => v == item).length == 0) {
                        delTemplateIds.value.push(item);
                    }
                });
                insItemTemplateIds.value.forEach((item) => {
                    if (insItemTemplateIdsCopy.value.filter((v) => v == item).length == 0) {
                        addTemplateIds.value.push(item);
                    }
                });
                editsecordstructure({
                    structureId: structureParam.value.id,
                    name: structureParam.value.name,
                    addTemplateIds: addTemplateIds.value,
                    delTemplateIds: delTemplateIds.value
                })
                    .then((res) => {
                        if (res.code === 200) {
                            ElMessage({
                                message: "修改成功",
                                type: "success"
                            });
                        }

                        secondLoading.value = false;
                        second.value = false;
                        refresh();
                    })
                    .catch(() => {
                        secondLoading.value = false;
                    });
            }
        }
    });
};
</script>
<style lang="less" scoped>
::v-deep(.table .el-table__body-wrapper .cell) {
    line-height: inherit;
    height: 100%;
}

.selectd {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    font-size: 14px;
    color: #ebebeb;
}

::v-deep(.el-tree-node__content > .el-tree-node__expand-icon) {
    position: absolute;
    opacity: 0;
}

::v-deep(.el-tree-node__content) {
    position: relative;
}

::v-deep(.el-tree-node__content):hover>.custom-tree-node>.operate {
    display: block;
}

.operate {
    display: none;
}

.pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.none {
    display: none;
}

.tree-flex {
    display: flex;
    align-items: center;
}

.image {
    width: 19px;
    height: 19px;
    margin-right: 10px;
}

.images {
    width: 16px;
    height: 19px;
    margin-right: 10px;
}

.icon {
    color: #2c80bf;
}

.custom-tree-node {
    display: flex;
    justify-content: space-between;
    width: 100%;
}

.ml-16 {
    margin-left: 16px;
}

.unchecked {
    font-size: 16px;
    font-weight: 400;
    color: #8c8c8c;
    cursor: pointer;
}

.select {
    font-size: 16px;
    font-weight: 600;
    color: #1b3646;
}

.second-btn {
    display: flex;
    justify-content: flex-end;
    padding-top: 16px;
}

.second-title {
    font-size: 14px;
    font-weight: 400;
    color: #1b3646;
}

.second-text {
    font-size: 14px;
    font-weight: 400;
    color: #595959;
    padding-left: 16px;
}

.flex {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .flex-text {
        font-size: 14px;
    }
}

.mr-8 {
    margin-right: 8px;
}

.checkbox {
    display: flex;
    flex-direction: column;
}

.check {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .check-title {
        font-size: 16px;
        font-weight: 600;
        color: #1b3646;
    }

    .check-btns {
        display: flex;

        .check-add {
            padding: 6px 25px;
            background: #00428e;
            font-size: 14px;
            font-weight: 400;
            color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
        }

        .check-delete {
            padding: 6px 25px;
            border: 1px solid #00428e;
            font-size: 14px;
            font-weight: 400;
            color: #00428e;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            margin-left: 16px;
        }
    }
}

.right-bottom-box {
    padding: 16px;
    background: #fff;
}

.bg {
    background: #fff;

    .box {
        padding: 16px;
    }
}

.right-top-box-btn {
    padding: 6px 25px;
    background: #00428e;
    font-size: 14px;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.period-title {
    font-size: 16px;
    font-weight: 600;
    color: #1b3646;
}

.period {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.right-top-box {
    padding: 16px;
    background: #fff;
    margin-bottom: 16px;
}

.scroll::-webkit-scrollbar {
    width: 4px;
}

.scroll::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.2);
}

.scroll::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
}

.option:hover {
    background: #f5f7fa;
}

.search {
    padding: 16px 0;
}

.box-left {
    padding: 16px;
    background: #fff;
    height: 100%;
    box-sizing: border-box;

    .btns {
        display: flex;
        padding-bottom: 16px;

        .btn-box {
            padding: 6px 11px;
            border: 1px solid #00428e;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
        }
    }
}

.box-top {
    padding: 16px;
    background: #fff;
    margin-bottom: 16px;

    .box-top-content {
        display: flex;

        .box-top-content-title {
            font-size: 14px;
            font-weight: 400;
            color: #1b3646;
        }

        .box-top-content-text {
            font-size: 14px;
            font-weight: 400;
            color: #595959;
            padding-left: 16px;
        }
    }

    .box-top-title {
        font-size: 16px;
        font-weight: 600;
        color: #1b3646;
        padding-bottom: 22px;
    }
}

.button {
    display: flex;
    justify-content: center;
}

.close {
    margin-left: 8px;
    width: 78px;
    height: 30px;
    border: 1px solid #00428e;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.closeText {
    color: #00428e;
    font-size: 14px;
    font-weight: 400;
}

.submit {
    width: 80px;
    height: 32px;
    background: #00428e;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.submitText {
    color: #ffffff;
    font-size: 14px;
    font-weight: 400;
}

::v-deep(.el-dialog__title) {
    color: #1b3646;
    font-weight: 600;
}

::v-deep(.el-form-item__label) {
    color: #1b3646;
}

::v-deep(.el-checkbox__label) {
    color: #1b3646;
    font-weight: 600;
}

::v-deep(.el-radio__label) {
    color: #1b3646;
    font-weight: 600;
}

::v-deep(.el-tree-node__expand-icon.expanded) {
    transform: rotate(0deg);
}
</style>
<style>
.el-message-box__btns {
    justify-content: center;
}

.el-message-box__title {
    font-weight: 600;
    color: #1b3646;
}

.el-message-box__message {
    color: #1b3646;
}

.el-message-box__btns .el-button--primary {
    background-color: #00428e;
}
</style>
